package com.sias.questionservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sias.common.common.ErrorCode;
import com.sias.common.constant.CommonConstant;
import com.sias.common.exception.BusinessException;
import com.sias.common.utils.SqlUtils;
import com.sias.model.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.sias.model.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.sias.model.model.entity.Question;
import com.sias.model.model.entity.QuestionSubmit;
import com.sias.model.model.entity.User;
import com.sias.model.model.enums.QuestionSubmitLanguageEnum;
import com.sias.model.model.enums.QuestionSubmitStatusEnum;
import com.sias.model.model.vo.QuestionSubmitVO;
import com.sias.model.model.vo.UserVO;
import com.sias.questionservice.mapper.QuestionSubmitMapper;
import com.sias.questionservice.service.QuestionService;
import com.sias.questionservice.service.QuestionSubmitService;
import com.sias.serviceclient.service.JudgeFeignClient;
import com.sias.serviceclient.service.UserFeignClient;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @author 123
 * @description 针对表【question_submit(题目提交)】的数据库操作Service实现
 * @createDate 2023-12-01 17:13:44
 */
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
        implements QuestionSubmitService {
  @Resource
  private QuestionService questionService;

  @Resource
  private UserFeignClient userService;

  @Resource
  @Lazy
  private JudgeFeignClient judgeFeignClient;

  /**
   * 提交题目
   *
   * @param questionSubmitAddRequest
   * @param loginUser
   * @return
   */
  @Override
  public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
    String language = questionSubmitAddRequest.getLanguage();
    QuestionSubmitLanguageEnum languageEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
    if (languageEnum == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言错误");
    }
    Long questionId = questionSubmitAddRequest.getQuestionId();
    // 判断实体是否存在，根据类别获取实体
    Question question = questionService.getById(questionId);
    if (question == null) {
      throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
    }
    // 是否已提交题目
    long userId = loginUser.getId();
    // 每个用户串行提交题目
    QuestionSubmit questionSubmit = new QuestionSubmit();
    questionSubmit.setLanguage(language);
    questionSubmit.setCode(questionSubmitAddRequest.getCode());
    questionSubmit.setJudgeInfo("{}");
    questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
    questionSubmit.setQuestionId(questionId);
    questionSubmit.setUserId(userId);
    questionSubmit.setQuestionId(questionId);
    boolean save = this.save(questionSubmit);
    if (!save) {
      throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据录入失败");
    }
    Long questionSubmitId = questionSubmit.getId();
    CompletableFuture.runAsync(() -> {
      judgeFeignClient.doJudge(questionSubmitId);
    });
    return questionSubmitId;
  }

  /**
   * 获取查询包装类
   *
   * @param questionSubmitQueryRequest
   * @return
   */
  @Override
  public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {

    QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
    if (questionSubmitQueryRequest == null) {
      return queryWrapper;
    }
    String language = questionSubmitQueryRequest.getLanguage();
    Integer status = questionSubmitQueryRequest.getStatus();
    Long questionId = questionSubmitQueryRequest.getQuestionId();
    Long userId = questionSubmitQueryRequest.getUserId();
    String sortField = questionSubmitQueryRequest.getSortField();
    String sortOrder = questionSubmitQueryRequest.getSortOrder();

    // 拼接查询条件
    queryWrapper.eq(StringUtils.isNotBlank(language), "language", language);
    queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
    queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
    queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(status) != null, "status", status);
    queryWrapper.eq("isDelete", false);
    queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
            sortField);
    return queryWrapper;
  }

  @Override
  public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
    QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
    // 1. 关联查询用户信息
    long userId = questionSubmit.getUserId();
    if (loginUser.getId() != userId && !userService.isAdmin(loginUser)) {
      questionSubmitVO.setCode(null);
    }
    UserVO userVO = userService.getUserVO(loginUser);
    questionSubmitVO.setUserVO(userVO);
    return questionSubmitVO;
  }

  @Override
  public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
    List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
    Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
    if (CollectionUtils.isEmpty(questionSubmitList)) {
      return questionSubmitVOPage;
    }
    List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream()
            .map(questionSubmit -> getQuestionSubmitVO(questionSubmit, loginUser)).collect(Collectors.toList());
    questionSubmitVOPage.setRecords(questionSubmitVOList);
    return questionSubmitVOPage;
  }

}




